package com.gxuwz.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.baomidou.mybatisplus.plugins.Page;

import java.util.List;

import org.apache.log4j.Logger;

/**
 * Created by mark on 16/11/30.
 * 采用阿里巴巴fastjson 进行对象&json字符串的序列化与反序列化
 */
public class FastJsonUtils {
	
	private static final Logger logger = Logger.getLogger(FastJsonUtils.class);
	
    /**
     * @param object
     * @return 将java对象转化为json字符串
     */
    public static String toJsonString(Object object) {
        return JSON.toJSONString(object,filter,SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 添加过滤器使数据库中字段为NULL的字段为""
     */
    private static ValueFilter filter = new ValueFilter() {
        @Override
        public Object process(Object obj, String s, Object v) {
            if (v == null)
                return "";
            return v;
        }
    };
    
    /**
     * @param json
     * @param cla
     * @param <T>
     * @return 将json字符串转化为java对象
     */
    public static <T> T toObject(String json, Class<T> cla) {
        return JSON.parseObject(json, cla);
    }

    public static <T> List<T> toList(String json, Class<T> t) {
        return JSON.parseArray(json, t);
    }
    
    public static <T> Page<T> getPage(String jsonString, Class<T> clz) {  
        try {  
           Page<T> page =  JSON.parseObject(jsonString,  
                    new TypeReference<Page<T>>() {  
                    });  
            //泛型类型调用paseObject的时候，使用parseObject可以转换Class，  
            // 但是后边传TypeReference或者Type就解析不出泛型类型了，需要再转换一次  
           logger.info("------------------"+page.getRecords());
            List<T> list = JSONArray.parseArray(page.getRecords().toString(), clz);  
            page.setRecords(list);  
            return page;  
        } catch (Exception e) {  
        	logger.info("FastJsonUtils getPage(..) ",e); 
        }
        logger.info("##############################"); 
        return null;  
    } 

}